package com.learn.security.modules.security.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.security.modules.security.LoginUser;
import com.learn.security.modules.security.LoginUserType;
import com.learn.security.modules.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * created by yuanjunjie on 2019/6/10 3:49 PM
 */
@Slf4j
@Component("jcAuthenticationSuccessHandler")
public class JCAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        LoginUser user = (LoginUser) authentication.getPrincipal();
        log.info("登录成功==>{}", user.getUserDto());


        if (user.getLoginUserType() == LoginUserType.WEIXIN_OPEN_ID) {
//            httpServletResponse.sendRedirect("/index.html");
            super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);
        } else {
            RequestCache requestCache = new HttpSessionRequestCache();
            SavedRequest savedRequest = requestCache.getRequest(httpServletRequest,httpServletResponse);
            String url = null;
            if(savedRequest != null){
                url = savedRequest.getRedirectUrl();
            }
            if (StrUtil.isEmpty(url)) {
                url = "/index.html";
            }

            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(R.ok()));
        }
    }
}
